﻿/***********************************************************
Copyright © 2015 Howyoung.
************************************************************
You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty.
************************************************************
您可以对所收受的本程序源代码，无论以何种媒介，复制与发布其完
整的复制物，然而您必须以显著及适当的方式在每一份复制物上发布
适当的著作权标示及无担保声明。
***********************************************************/
using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace MinecraftSavesBackup
{
    public partial class EnterBackupAddress : Form
    {
        public EnterBackupAddress()
        {
            InitializeComponent();
        }

        private void backupAddressTextBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (backupAddressTextBox.Text.Length >= 2)
                {
                    string drive = backupAddressTextBox.Text.Substring(0, 2);
                    System.IO.DriveInfo driveInfo = new System.IO.DriveInfo(drive);
                    decimal availableFreeSpace = Math.Round(Convert.ToDecimal(driveInfo.AvailableFreeSpace) / 1024 / 1024 / 1024, 2);
                    decimal totalSize = Math.Round(Convert.ToDecimal(driveInfo.TotalSize) / 1024 / 1024 / 1024, 2);
                    availableFreeSpaceLabel.Text = "可用空间: " + Convert.ToString(availableFreeSpace) + " GB";
                    totalSizeLabel.Text = "磁盘容量: " + Convert.ToString(totalSize) + " GB";
                    int diskUseSize = Convert.ToInt32(100 - availableFreeSpace / totalSize * 100);
                    diskUseSizeProgressBar.Value = diskUseSize;
                    diskUseSizeLabel.Text = Convert.ToString(diskUseSize) + "%";
                }
            }
            catch (Exception)
            {
                //忽略错误
            }
        }

        private void browseLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                backupAddressTextBox.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void backButton_Click(object sender, EventArgs e)
        {
            EnterSavesAddress EnterSavesAddress = new EnterSavesAddress();
            EnterSavesAddress.Show();
            Close();
        }

        private void finishButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (backupAddressTextBox.Text != "")
                {
                    //记录备份地址
                    if (backupAddressTextBox.Text.EndsWith("BackupSaves\\"))
                    {
                        Properties.Settings.Default.BackupAddress = backupAddressTextBox.Text;
                    }
                    else if (backupAddressTextBox.Text.EndsWith("BackupSaves"))
                    {
                        Properties.Settings.Default.BackupAddress = backupAddressTextBox.Text + "\\";
                    }
                    else if (backupAddressTextBox.Text.EndsWith("\\"))
                    {
                        Properties.Settings.Default.BackupAddress = backupAddressTextBox.Text + "BackupSaves\\";
                    }
                    else
                    {
                        Properties.Settings.Default.BackupAddress = backupAddressTextBox.Text + "\\BackupSaves\\";
                    }
                    System.IO.Directory.CreateDirectory(Properties.Settings.Default.BackupAddress);
                    //保存设置
                    Properties.Settings.Default.Save();
                    //初次备份过程
                    if (MessageBox.Show("配置完成，是否立即执行一次备份？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        finishButton.Enabled = false;
                        finishButton.Text = "请稍后(0%)";
                        backButton.Enabled = false;
                        browseLinkLabel.Enabled = false;
                        backgroundWorker.RunWorkerAsync();
                    }
                    else
                    {
                        Properties.Settings.Default.Initialization = false;
                        Properties.Settings.Default.Save();
                        Main Main = new Main();
                        Main.Show();
                        Close();
                    }
                }
                else
                {
                    MessageBox.Show("请填写备份地址！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                HandlingErrors.Record(ex);
            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string backupName, year = Convert.ToString(DateTime.Now.Year),
                           month = Convert.ToString(DateTime.Now.Month),
                           day = Convert.ToString(DateTime.Now.Day),
                           hour = Convert.ToString(DateTime.Now.Hour),
                           minute = Convert.ToString(DateTime.Now.Minute),
                           second = Convert.ToString(DateTime.Now.Second);
                if (month.Length == 1) month = "0" + month;
                if (day.Length == 1) day = "0" + day;
                if (hour.Length == 1) hour = "0" + hour;
                if (minute.Length == 1) minute = "0" + minute;
                if (second.Length == 1) second = "0" + second;
                backupName = year + month + day + hour + minute + second;
                double count = 0;
                double all = Properties.Settings.Default.BackupDirectoryAddress.Count;
                foreach (string directoryName in Properties.Settings.Default.BackupDirectoryAddress)
                {
                    string gameName = directoryName.Replace(Properties.Settings.Default.SaveAddress, null);
                    string backupPath = Properties.Settings.Default.BackupAddress + backupName;
                    string zipPath = backupPath + "\\" + gameName + ".saves";
                    System.IO.Directory.CreateDirectory(backupPath);
                    Compression.CompressFolder(directoryName, zipPath);
                    count++;
                    backgroundWorker.ReportProgress(Convert.ToInt32(count / all * 100));
                }
            }
            catch (Exception ex)
            {
                HandlingErrors.ErrorMessage(ex, "请尝试重新备份。");
                HandlingErrors.Record(ex);
            }
        }

        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            finishButton.Text = "请稍后(" + Convert.ToString(e.ProgressPercentage) + "%)";
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            finishButton.Enabled = true;
            finishButton.Text = "下一步(&N)";
            backButton.Enabled = true;
            browseLinkLabel.Enabled = true;
            Properties.Settings.Default.Initialization = false;
            Properties.Settings.Default.Save();
            Main Main = new Main();
            Main.Show();
            Close();
        }
    }
}
